<template >
	<!-- eslint-disable vue/no-v-model-argument -->
	<div class="page_container">
		<!-- 搜索栏 开始 -->
		<div class="search_container">
			<AutoForm
				ref="searchForm"
				:schema="searchFormSchema"
				:source="searchFormSource"
				:formOption="{ inline: true }"
				style="padding: 0 10px 0 0"
				size="mini"
				formItemWidth="200px"
			>
				<template #submitFormItem>
					<el-form-item>
						<el-button type="primary" size="small" @click="searchSubmit()">查询</el-button>
						<el-button size="small" @click="clearSearchForm()">重置</el-button>
					</el-form-item>
				</template>
			</AutoForm>
		</div>
		<!-- 搜索栏 结束 -->

		<!-- 按钮工具栏 开始 -->
		<div class="action_container" refs="actionContainer">
			<!-- 此处插入功能按钮等...
                可以使用权限套件控制显示
                v-anyPermission="[]"
                checkPermsisions([])
             -->
			<el-button type="primary" size="small" @click="showAddDrawer = true"> 新增{{ pageTitle }} </el-button>
		</div>
		<!-- 按钮工具栏 结束 -->

		<!-- 数据展示表格 开始 -->
		<div class="table_container">
			<AutoTable
				:source="recordData.results"
				:schema="tableSchema"
				:rowEdit="handleEdit"
				:rowDelete="rowDelete"
				:loading="tableLoading"
			>
				<template v-slot:is_active="{ data }">
					<el-table-column :label="data.item.value" :prop="data.item.key" align="center">
						<template #default="scope">
							<a v-if="scope.row.is_active" class="el-icon-circle-check" style="color: #67c23a"></a>
							<a v-else class="el-icon-circle-close" style="color: #f56c6c"></a>
						</template>
					</el-table-column>
				</template>
			</AutoTable>
		</div>
		<!-- 数据展示表格 结束 -->

		<!-- 分页 开始 -->
		<div class="pagination_container" refs="paginationContainer">
			<el-pagination
				@size-change="sizeChange()"
				@current-change="currentChange()"
				background
				layout="prev, pager, next, sizes, jumper"
				:total="recordData.count"
				v-model:pageSize="recordData.page_size"
				v-model:currentPage="recordData.page"
				:hide-on-single-page="false"
			>
			</el-pagination>
		</div>
		<!-- 分页 结束 -->

		<!-- 添加弹出层 开始 -->
		<el-drawer :title="'添加' + pageTitle" v-model="showAddDrawer" :show-close="false" destroy-on-close>
			<AutoForm
				ref="addForm"
				:schema="formSchema"
				:source="addFormSource"
				:submit="addSubmit"
				style="padding: 0 10px 0 0"
				size="small"
				formItemWidth="360px"
			>
				<!-- <template v-slot:字段名="{ data }">
					<el-form-item label="自定义" :key="field_name" :prop="field_name">
						<el-input v-model="data.source[field_name]" v-bind="data.propertie.props"></el-input>
					</el-form-item>
				</template> -->
			</AutoForm>
		</el-drawer>
		<!-- 添加弹出层 结束 -->

		<!-- 修改弹出层 开始 -->
		<el-drawer :title="'修改' + pageTitle" v-model="showChangeDrawer" :show-close="false" destroy-on-close>
			<AutoForm
				ref="changeForm"
				:schema="formSchema"
				:source="changeFormSource"
				:submit="changeSubmit"
				style="padding: 0 10px 0 0"
				size="small"
				formItemWidth="360px"
			>
			</AutoForm>
		</el-drawer>
		<!-- 修改弹出层 结束 -->
	</div>
</template>
<script>
import { ElMessage } from 'element-plus'
import { list, remove, retrieve, create, put, patch } from '@/apis/curd'
import { anyPermission } from '@/utils/permission'
import { datetimeFormat } from '@/utils/tools'
import AutoTable from '@/common/components/AutoTable'
import AutoForm from '@/common/components/AutoForm'

export default {
	name: 'User',
	components: {
		AutoTable,
		AutoForm,
	},
	data() {
		return {
			// 用于自动设置表格高度
			tableHeight: 100,
			reloadKey: 1,
			// 页面配置项
			pageTitle: '学校',
			uri: 'school/school', // 请求的基础地址 /<uri>
			key: 'id', // 加在请求后面的主键key /<uri>/<key>
			showAddDrawer: false, // 控制是否打开添加表单抽屉
			showChangeDrawer: false, // 控制是否打开修改表单抽屉
			selectRow: null, // 编辑/删除时行数据会保存在这里
			tableLoading: false,
			recordData: { page: 1, page_size: 20, count: 0, results: [] }, // 展示数据及分页数据
			tableSchema: [
				{ key: 'name', value: '学校名称' },
				{ key: 'note', value: '学校描述' },
				{ key: 'president', value: '校长' },
			], // Table
			searchFormSource: {},
			searchFormSchema: {
				properties: {
					name: {
						label: '学校名称',
					},
				},
			}, // 搜索工具栏数据
			addFormSource: {},
			changeFormSource: {},
			formSchema: {
				properties: {
					name: {
						label: '教室名称',
						rules: [
							{ required: true, message: '此项必填', trigger: 'blur' },
							{ min: 2, max: 18, message: '请输入 2 到 18 个字符', trigger: 'blur' },
						],
					},
					note: {
						label: '学校描述',
						type: 'text',
					},
					president_id: {
						label: '校长',
						type: 'select',
						props: {
							uri: 'auth/search_user',
							isRemote: true,
							lookup: 'nickname',
						},
					},
				},
			},
		}
	},
	mounted() {
		// 渲染结束后钩子函数
		this.searchSubmit()
		this.initFormSource()
	},
	computed: {
		addFormSchema() {
			return this.formSchema
		},
		changeFormSchema() {
			return this.formSchema
		},
	},
	methods: {
		initFormSource() {
			// 初始化表单数据
			for (let i in this.changeFormSchema.properties) {
				this.changeFormSource[i] = null
			}
			for (let i in this.addFormSchema.properties) {
				this.addFormSource[i] = null
			}
			for (let i in this.searchFormSchema.properties) {
				this.searchFormSource[i] = null
			}
		},
		// 清空搜索工具栏
		clearSearchForm() {
			for (let i in this.searchFormSchema.properties) {
				this.searchFormSource[i] = null
			}
		},
		// 搜索请求
		searchSubmit() {
			// 构造分页及筛选数据
			this.tableLoading = true
			let data = { page: this.recordData.page, page_size: this.recordData.page_size }
			for (let i in this.searchFormSource) {
				let val = this.searchFormSource[i]
				if (val) {
					data[i] = val
				}
			}
			//  发起请求
			list(this.uri, data, false)
				.then(res => {
					// 处理成功数据
					this.recordData = res.data.recordData
					this.addData.source = res.data.addData
					this.changeData.source = res.data.changeData
					this.searchData.source = res.data.searchData
					this.tableLoading = false
				})
				.catch(respons => {
					// 处理失败数据
					this.tableLoading = false
				})
		},
		// 点击删除键时触发的事件
		rowDelete(index, row) {
			remove(this.uri, row[this.key])
				.then(res => {
					if (res.status) {
						this.recordData.results.splice(index, 1)
						ElMessage.success({
							message: '删除成功',
						})
					} else {
						ElMessage.error({
							message: res.message,
						})
					}
				})
				.catch(respons => {
					console.log(respons)
				})
		},
		// 分页的记录条数发生变化时触发
		sizeChange() {
			this.searchSubmit()
		},
		// 分页的页码发生变化时触发
		currentChange() {
			this.searchSubmit()
		},
		// 点击编辑时触发的方法
		handleEdit(index, row) {
			retrieve(this.uri, row[this.key]).then(res => {
				if (res.status) {
					this.selectRow = row
					this.showChangeDrawer = true
					for (let i in this.changeFormSchema.properties) {
						this.changeFormSource[i] = res.data[i]
					}
				} else {
					ElMessage.error({
						message: res.message,
					})
				}
			})
		},
		// 执行添加提交
		addSubmit() {
			this.$refs['addForm'].validate(valid => {
				if (valid) {
					if (this.addFormSource.birthday) {
						console.log(1)
						this.addFormSource.birthday = datetimeFormat(this.addFormSource.birthday, 'yyyy-M-d')
					}
					create(this.uri, this.addFormSource).then(res => {
						if (res.status) {
							ElMessage.success({
								message: '添加成功',
							})
							this.searchSubmit()
							this.showAddDrawer = false
						} else {
							ElMessage.error({
								message: res.message,
							})
						}
					})
				}
			})
		},
		// 执行修改提交
		changeSubmit() {
			this.$refs['changeForm'].validate(valid => {
				if (valid) {
					if (this.changeFormSource.birthday) {
						this.changeFormSource.birthday = datetimeFormat(this.changeFormSource.birthday, 'yyyy-M-d')
					}
					patch(this.uri, this.selectRow[this.key], this.changeFormSource).then(res => {
						if (res.status) {
							ElMessage.success({
								message: '修改成功',
							})
							this.searchSubmit()
							this.showChangeDrawer = false
						} else {
							ElMessage.error({
								message: res.message,
							})
						}
					})
				}
			})
		},
		//  工具方法
		checkPermsisions(values) {
			// 检查是否有权限
			if (Array.isArray(values)) {
				return anyPermission(values)
			}
			return false
		},
		concatList(o, t) {
			// 合并数组 arry
			if (Array.isArray(o) && Array.isArray(t)) {
				return o.concat(t)
			} else if (Array.isArray(o)) {
				return o
			} else if (Array.isArray(t)) {
				return t
			} else {
				return []
			}
		},
	},
}
</script>
<style lang='scss' scoped>
.search_container {
	padding: 1rem 1rem 0 1rem;
	background-color: white;
	border-bottom: 1px #f2f6fc solid;
	line-height: 1rem;
}
.action_container {
	padding: 0.5rem 1rem;
	background-color: #f5f7fa99;
	background-color: white;
}
.table_container {
	// padding: 0rem 2rem 1rem 2rem;
	background-color: white;
	padding: 0 1rem;
}
.pagination_container {
	padding: 1rem 4rem 1rem 0rem;
	background-color: white;
	text-align: center;
}
.add_form,
.change_form {
	padding-right: 2rem;
}
:deep(.el-drawer__body) {
	overflow-x: auto;
}
.inline-block {
	display: inline-block;
}
</style>